package com.heima.comment.filter;

import com.heima.common.exception.CustException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.whitelist.WhiteList;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author XHui
 * @Since 2024/3/4 18:51
 * @Version 1.0
 */
@Order(2)
@Component
@WebFilter(filterName = "appUserIdFilter", urlPatterns = {"/*"})
public class AppUserLoginFilter extends GenericFilterBean {

    private static List<String> whiteList;

    static {
        whiteList = new ArrayList<>();
        whiteList.add("/load");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws ServletException, IOException {

        // 1. 过滤白名单
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null && !isPassByWhiteList(requestURI)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "用户必须登录");
        }
        // 2. 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean isPassByWhiteList(String path){
        for (String item : whiteList) {
            if (path.contains(item)){
                return true;
            }
        }
        boolean pass = WhiteList.isPass(WhiteList.Knife4jWhiteList.list(), path);
        return pass;
    }
}
